package com.imut.oa;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imut.oa.pojo.entity.Attendance;
import com.imut.oa.pojo.entity.User;
import com.imut.oa.service.AttendanceService;
import com.imut.oa.service.UserService;
import com.imut.oa.service.impl.AttendanceServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class AttendanceCheckJob {

    private final UserService userService;
    private final AttendanceServiceImpl attendanceService;

    @Scheduled(cron = "0 12 15 * * ?") // 每天23:30执行
    @Transactional(rollbackFor = Exception.class)
    public void checkDailyAttendance() {
        log.info("开始执行每日考勤检查任务");

        // 1. 获取所有在职员工
        List<Long> employeeIds = getActiveEmployeeIds();

        // 2. 获取当天日期
        LocalDate today = LocalDate.now();

        // 3. 检查每个员工的考勤记录
        List<Attendance> absences = employeeIds.stream()
                .map(employeeId -> checkEmployeeAttendance(employeeId, today))
                .filter(attendance -> attendance != null)
                .collect(Collectors.toList());

        // 4. 批量保存缺勤记录
        if (!absences.isEmpty()) {
            attendanceService.saveBatch(absences);
            log.info("生成缺勤记录 {} 条", absences.size());
        }

        log.info("考勤检查任务执行完成");
    }

    private List<Long> getActiveEmployeeIds() {
        return userService.list(new LambdaQueryWrapper<User>()
                        .select(User::getId)
                        .eq(User::getUserStatus, 0)
                        .eq(User::getIsDelete, 0))
                .stream()
                .map(User::getId)
                .collect(Collectors.toList());
    }

    private Attendance checkEmployeeAttendance(Long employeeId, LocalDate date) {
        // 查询当天的所有考勤记录
        List<Attendance> records = attendanceService.list(
                new LambdaQueryWrapper<Attendance>()
                        .eq(Attendance::getEmployeeId, employeeId)
                        .apply("DATE(clockTime) = {0}", date)
        );

        // 统计打卡类型
        boolean hasClockIn = records.stream().anyMatch(r -> r.getAttendanceType() == 0);
        boolean hasClockOut = records.stream().anyMatch(r -> r.getAttendanceType() == 1);

        // 生成缺勤记录逻辑
        if (records.isEmpty()) {
            return buildAbsenceRecord(employeeId, date, 3); // 全天缺勤
        } else if (hasClockIn && !hasClockOut) {
            return buildAbsenceRecord(employeeId, date, 5); // 缺下班打卡
        }
        return null;
    }

    private Attendance buildAbsenceRecord(Long employeeId, LocalDate date, int status) {
        return Attendance.builder()
                .employeeId(employeeId)
                .clockTime(LocalDateTime.now())// 设置打卡时间为当天的00:00:00
                .latitude(BigDecimal.ZERO)
                .longitude(BigDecimal.ZERO)
                .attendanceType(status == 3 ? 0 : 1) // 根据状态设置类型
                .status(status)
                .remark("系统自动生成缺勤记录")
                .createTime(LocalDateTime.now())
                .build();
    }
}